<template>
  <div class="row input-field-upload-btn">
    <q-uploader
      @uploaded="uploaded"
      ref="uploader"
      :factory="factoryFn"
      auto-upload
      :class="`q-ma-xs ${hasError ? 'input-field--error' : ''}`"
    >
      <template v-slot:list>
        <q-btn
          type="a"
          icon="cloud_upload"
          dense
          flat
          class="upload-btn"
          :label="$t('点击上传')"
        >
          <q-uploader-add-trigger v-if="!Field.ReadOnly" />
        </q-btn>
      </template>
    </q-uploader>
  </div>
</template>

<script>
import { UploaderMixin, InputFieldMixin } from 'eis-admin-mixins';

export default {
  name: 'InputFieldUploadBtn',
  mixins: [UploaderMixin, InputFieldMixin],
  fieldInfo: {
    Category: 'Upload',
    Label: '上传按钮',
    Value: 'UploadBtn',
    Extra: [
      {
        Type: 'String',
        Label: '接口路径',
        Name: 'Options.url',
      },
      {
        Type: 'String',
        Label: '支持的文件类型',
        Name: 'Options.Ext',
        Default: 'pdf,doc,docx',
      },
      {
        Type: 'String',
        Label: '最大文件大小',
        Name: 'MaxValue',
        Default: '10m',
      },
      {
        Type: 'Boolean',
        Label: '上传后刷新页面',
        Name: 'Options.RefreshAfterUploaded',
        Default: false,
      },
    ],
    Description: '',
  },
  methods: {
    validate() {
      if (this.Field.Required) {
        this.hasError = this.$refs.uploader.files.length <= 0;
        return this.$refs.uploader.files.length > 0;
      }

      const rules = Array.isArray(typeof this.Field.Rules)
        ? this.Field.Rules
        : [this.Field.Rules];

      let isValid = true;
      for (let i = 0; i < rules.length; i += 1) {
        const r = rules[i];

        if (typeof r === 'function') {
          isValid = isValid && r(this.$refs.uploader.files);
        }
      }

      this.hasError = !isValid;
      return isValid;
    },
    factoryFn() {
      return {
        url: this.Field.Options?.url || `${this.ctx.config.baseUrl}/upload`,
        fieldName: 'file',
      };
    },
    uploaded(info) {
      if (info && info.files && info.files.length && info.files[0].xhr) {
        const { xhr } = info.files[0];
        let res;
        if (xhr.response) {
          if (res && res.msg === 'OK' && this.Field.Options?.RefreshAfterUploaded) {
            window.location.reload();
          }
        }
      }
    },
  },
};
</script>
